import axios from 'axios'
import store from '@/store'
import router from '@/router'

// import store from '@/store/userstores'
const instance = axios.create({
  baseURL: 'http://toutiao.itheima.net',
  timeout: 5000
})
// 添加请求拦截器
instance.interceptors.request.use(
  function(config) {
    // 在发送请求之前做些什么
    const token = store.state.user.token.token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  function(error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(
  function(response) {
    // 对响应数据做点什么

    return response.data
  },
  async function(error) {
    // 对响应错误做点什么
    if (error.response.status === 401) {
      console.log(error.config)
      if (store.state.user.token.refresh_token) {
        try {
          const refresh = store.state.user.token.refresh_token
          const res = await axios({
            url: 'http://toutiao.itheima.net/v1_0/authorizations',
            method: 'PUT',
            headers: {
              Authorization: `Bearer ${refresh}`
            }
          })
          store.commit('user/RemoveToken')
          store.commit('user/settoken', {
            refresh_token: refresh,
            token: res.data.data.token
          })
          return instance(error.config)
        } catch {
          removetokenaxios()
        }
      } else {
        removetokenaxios()
      }

      // console.log(111)
      // store.commit('user/RemoveToken')
      // router.push({
      //   path: '/login',
      //   query: {
      //     back: router.currentRoute.fullPath,
      //     flag: true
      //   }
      // })
    } else {
      return Promise.reject(error)
    }
  }
)
export default instance

function removetokenaxios() {
  store.commit('user/RemoveToken')
  router.push({
    path: '/login',
    query: {
      back: router.currentRoute.fullPath,
      flag: true
    }
  })
}
